#!/bin/bash

# 引入配置文件
source config.sh

# 日志文件路径
LOG_FILE="$LOG_DIR/manage-db-users.log"

# 创建日志目录
mkdir -p $LOG_DIR
touch $LOG_FILE

# 日志记录函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $LOG_FILE
}

# 错误处理函数
error_exit() {
    log "ERROR: $1"
    exit 1
}

# 添加数据库用户
add_db_user() {
    local USERNAME=$1
    local PASSWORD=$2
    local DATABASE=$3

    log "Adding database user: $USERNAME..."

    mysql -u root -p$DB_ROOT_PASS <<EOF
CREATE USER IF NOT EXISTS '$USERNAME'@'localhost' IDENTIFIED BY '$PASSWORD';
GRANT ALL PRIVILEGES ON $DATABASE.* TO '$USERNAME'@'localhost';
FLUSH PRIVILEGES;
EOF

    if [ $? -ne 0 ]; then
        error_exit "Failed to add database user: $USERNAME"
    fi

    log "Database user $USERNAME added successfully."
}

# 删除数据库用户
delete_db_user() {
    local USERNAME=$1

    log "Deleting database user: $USERNAME..."

    mysql -u root -p$DB_ROOT_PASS <<EOF
DROP USER IF EXISTS '$USERNAME'@'localhost';
FLUSH PRIVILEGES;
EOF

    if [ $? -ne 0 ]; then
        error_exit "Failed to delete database user: $USERNAME"
    fi

    log "Database user $USERNAME deleted successfully."
}

# 修改数据库用户密码
change_db_user_password() {
    local USERNAME=$1
    local NEW_PASSWORD=$2

    log "Changing password for database user: $USERNAME..."

    mysql -u root -p$DB_ROOT_PASS <<EOF
ALTER USER '$USERNAME'@'localhost' IDENTIFIED BY '$NEW_PASSWORD';
FLUSH PRIVILEGES;
EOF

    if [ $? -ne 0 ]; then
        error_exit "Failed to change password for database user: $USERNAME"
    fi

    log "Password for database user $USERNAME changed successfully."
}

# 主逻辑
if [ "$1" == "add" ]; then
    if [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ]; then
        error_exit "Usage: $0 add <username> <password> <database>"
    fi
    add_db_user $2 $3 $4
elif [ "$1" == "delete" ]; then
    if [ -z "$2" ]; then
        error_exit "Usage: $0 delete <username>"
    fi
    delete_db_user $2
elif [ "$1" == "change-password" ]; then
    if [ -z "$2" ] || [ -z "$3" ]; then
        error_exit "Usage: $0 change-password <username> <new_password>"
    fi
    change_db_user_password $2 $3
else
    echo "Usage: $0 [add|delete|change-password] <arguments>"
    exit 1
fi

log "Database user management operation completed successfully!"